import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { WeekWorkService } from './weekwork.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-weekwork-table',
    templateUrl: './weekwork.table.component.html',
    styleUrls: ['./weekwork.component.less'],
})
export class WeekworkTableComponent implements OnInit {
    pageIndex: any = 1;
    pageSize = '50';
    pageTotal: any = '';
    queryData: any = {};
    tableData: any = [];
    hisTableData: any = [];
    hisVisible = false;
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
    addData: any = [];
    optConfig: any = {}
    statusList: any = {};
    tableLoading = false;
    hisScroll = { y: '50vh', };
    headBarCfg = {
        gq: {
            gqbz: ['add', 'tibao', 'delete', 'reset']
        },
        cj: {
            cjbz: ['add', 'tibao', 'delete', 'reset'],
            gqsp: ['pizhun', 'bohui'],
        },
        gcs: {
            jskbz: ['add', 'tibao', 'delete', 'reset'],
            cjsp: ['pizhun', 'bohui'],
            cjck: [],
            gqck: [],
        },
        jskz: {
            jsksp: ['pizhun', 'bohui'],
            jskck: [],
            cjck: [],
            gqck: [],
        },
        dz: {
            jsksp: ['pizhun', 'bohui'],
            jskck: [],
            cjck: [],
            gqck: [],
        },
    };
    content = '';
    userInfo = JSON.parse(this.ls.get('loginInfo'));
    gqList = [];
    cjList = [];
    addVisible = false;

    @Input() set inputParam(v) {
        if (!v) {
            return;
        }
        if (v.page) {
            this.pageIndex = v.page;
        }
        if (v.rows) {
            this.pageSize = v.rows;
        }
        Object.assign(this.queryData, v);
        setTimeout(() => {
            this.query();
        }, 0);
    };

    @Input() user: { userType, tab };
    @Input() bmList;
    @Output() dbclick = new EventEmitter();

    ngOnInit(): void {
        this.initOptConfig();
        this.initStatusList();
    }

    constructor(
        private weekWorkService: WeekWorkService,
        private message: NzMessageService,
        private modalService: NzModalService,
        private http: _HttpClient,
        private ls: LocalStorage,
        private datePipe: DatePipe
    ) { }

    initStatusList() {
        this.statusList = {
            '0': '修改',
            '1': '提报',
            '2': '车间批准',
            '3': '车间驳回',
            '4': '段批准',
            '5': '段驳回',
            '6': '技术科批准',
            '7': '技术科驳回'
        };
    }

    initOptConfig() {
        const deleteCfg = {
            name: '删除',
            value: ['0', '3', '5', '7'],
            optfunc: this._optFunc_delete,
        };
        const tibaoCfg: any = {
            name: '提报',
            value: ['0', '3', '5', '7'],
            optfunc: this._optFunc_tibao
        };
        const pizhunCfg: any = {
            name: '批准',
            value: ['1'],
            optfunc: this._optFunc_pizhun
        };
        const bohuiCfg: any = {
            name: '驳回',
            value: ['1'],
            optfunc: this._optFunc_bohui
        };
        const resetCfg: any = {
            name: '重置',
            value: ['0', '3', '5', '7'],
            optfunc: this._optFunc_reset,
            checkFunc: (rows) => {
                if (rows.length !== 1) {
                    this.message.warning('您只能选择一项进行该操作')
                    return false;
                } else {
                    return true;
                }
            }
        };

        switch (this.user.userType) {
            case 'jskz':
                pizhunCfg.value = ['1', '5']
                deleteCfg.value = ['0', '5'];
                tibaoCfg.value = ['0', '5'];
                break;
            case 'dz':
                pizhunCfg.value = ['1', '6']
                bohuiCfg.value = ['1', '6']
                deleteCfg.value = ['0'];
                tibaoCfg.value = ['0'];
                break;
            case 'gcs':
                deleteCfg.value = ['0', '7'];
                tibaoCfg.value = ['0', '7'];
                break;
            case 'cj':
                deleteCfg.value = ['0', '7'];
                tibaoCfg.value = ['0', '7'];
                break;
            case 'gq':
                deleteCfg.value = ['0', '3'];
                tibaoCfg.value = ['0', '3'];
                break;
            default:
                break;
        }
        this.optConfig = {
            'delete': deleteCfg,
            'tibao': tibaoCfg,
            'pizhun': pizhunCfg,
            'bohui': bohuiCfg,
            'reset': resetCfg,
        }
    }

    btnShowCheck(btnType) {
        return this.headBarCfg[this.user.userType][this.user.tab].includes(btnType);
    }

    readyload(page, size) {
        this.pageIndex = page;
        this.pageSize = size;
        this.query();
    }

    getQueryOb(param) {
        const queryParamCfg = {
            gq: {
                gqbz: {
                    orgType: '',
                    queryType: 'bianzhi',
                }
            },
            cj: {
                cjbz: {
                    orgType: '2',
                    queryType: 'bianzhi',
                },
                gqsp: {
                    orgType: '',
                    queryType: 'shenpi',
                },
            },
            gcs: {
                jskbz: {
                    orgType: '3',
                    queryType: 'bianzhi',
                },
                cjsp: { // 车间审批
                    orgType: '',
                    queryType: 'shenpi',
                },
                cjck: { // 车间查看
                    orgType: '2',
                    queryType: 'bianzhi',
                },
                gqck: { // 工区查看
                    orgType: '1',
                    queryType: 'bianzhi',
                },
            },
            jskz: {
                jsksp: {
                    orgType: '3',
                    queryType: 'shenpi',
                },
                jskck: { // 技术科查看
                    orgType: '3',
                    queryType: 'bianzhi',
                },
                cjck: { // 车间查看
                    orgType: '2',
                    queryType: 'bianzhi',
                },
                gqck: { // 工区查看
                    orgType: '1',
                    queryType: 'bianzhi',
                },
            },
            dz: {
                jsksp: {
                    orgType: '3',
                    queryType: 'shenpi',
                },
                jskck: { // 技术科查看
                    orgType: '3',
                    queryType: 'bianzhi',
                },
                cjck: { // 车间查看
                    orgType: '2',
                    queryType: 'bianzhi',
                },
                gqck: { // 工区查看
                    orgType: '1',
                    queryType: 'bianzhi',
                },
            },

        }
        const qp = queryParamCfg[this.user.userType][this.user.tab];
        const type = qp.queryType;
        param.orgType = qp.orgType;
        let ob;
        switch (type) {
            case 'bianzhi':
                ob = this.weekWorkService.query(param);
                break;
            case 'shenpi':
                ob = this.weekWorkService.query_sp(param);
                break;
            default:
                break;
        }
        return ob;
    }

    // 第一页列表数据
    query() {

        const param: any = {
            page: this.pageIndex,
            limit: this.pageSize,
        };
        if (this.queryData._ym) {
            const ym = this.getYm(this.queryData._ym);
            param.vcYear = ym[0];
            param.vcMonth = ym[1];
        }
        Object.assign(param, this.queryData);
        this.removeUselessFields(param);
        const ob = this.getQueryOb(param);

        this.tableLoading = true;
        ob.subscribe((res) => {
            this.tableLoading = false;
            if (res.msg === 'Ok') {
                this.tableData = res.data;
                if (res.count) {
                    this.pageTotal = res.count;
                }
            }
        })
    }

    /**
     * 获取日期中的年月
     * @param date 日期
     */
    getYm(date: Date) {
        const y = date.getFullYear();
        const m = date.getMonth() + 1;
        return [y, m]
    }
    checkAll(v) {
        this.tableData.forEach(row => {
            row.checked = v;
        });
    }

    // 显示[新编]弹出层
    hisShow(row) {
        this.hisVisible = true;
        this.getHistory(row);
    }

    /**
     * 删除私立字段
     * @param param 参数
     */
    removePrivateFields(param) {
        Object.keys(param).forEach(key => {
            if (!(key.indexOf('_'))) {
                delete param[key];
            }
        });
    }

    /**
     * 删除null字段
     * @param param 参数
     */
    removeUselessFields(param) {
        Object.keys(param).forEach(key => {
            if (!param[key]) {
                delete param[key];
            }
        });
    }

    date2Str(param) {
        param.dtWsdate = param._dtWsdate ? this.datePipe.transform(param._dtWsdate, 'yyyy-MM-dd') : '';
        param.dtWedate = param._dtWedate ? this.datePipe.transform(param._dtWedate, 'yyyy-MM-dd') : '';
    }

    resetConfirm() {
        this.modalService.confirm({
            nzTitle: `重置确认`,
            nzWidth: '600',
            nzContent: "重置后将不可恢复,确认重置周计划吗？",
            nzOnOk: () => {
                this.resetOk();
            }
        })
    }

    // 保存[新编]弹出层
    resetOk() {
        if (this.addData._ym) {
            const ym = this.getYm(this.addData._ym);
            const param: any = {
                year: ym[0] + '',
                month: ym[1] + ''
            }
            Object.assign(param, this.addData);
            this.removePrivateFields(param);
            this.weekWorkService.reset(param).subscribe(res => {
                if (res.msg === 'Ok') {
                    this.message.success('新增成功');
                    this.addCancel();
                    this.query();
                } else {
                    this.message.warning('新增失败');
                }
            })
        }
    }

    // 关闭弹出层
    hisCancel() {
        this.hisVisible = false;
    }

    getChecked() {
        const delRows = this.tableData.filter(row => row.checked);
        return delRows;
    }

    getGq() {
        const param = { orgId: this.queryData.cjorg || this.userInfo.VC_ORG$ID, cjandgq: 1 };
        this.weekWorkService.getgongquByCjId(param).subscribe(res => {
            this.gqList = res;
        })
    }
    getCj() {
        this.weekWorkService.getCjList().subscribe(res => {
            this.cjList = res;
        })
    }

    /**
     * 操作检验
     * @param optType 操作类型
     * @param checkedRows 勾选条目
     */
    optCheck(optType, checkedRows) {
        let check = true;
        const optName = this.optConfig[optType].name;
        if (!checkedRows.length) {
            this.message.warning(`请先勾选条目以执行 ${optName} 操作`);
            check = false;
        } else {
            const checkFunc = this.optConfig[optType].checkFunc;
            if (checkFunc) {
                const res = checkFunc.call(this, checkedRows);
                if (res === false) {
                    return false;
                }
            }
            const optSta = this.optConfig[optType].value;
            const index = checkedRows.findIndex(row => {
                return !optSta.includes(row.vcStatus);
            })
            const statusList = this.statusList;
            const qsStaStr = optSta.map(el => statusList[el]);
            if (index !== -1) {
                this.message.warning(`您只能${optName}状态为: ${qsStaStr.join('、')} 的条目，勾选项中存在不可${optName}项`,
                    { nzDuration: 5000 });
                check = false;
            }
        }
        return check;
    }

    optAll(optType, content?) {
        const checkedRows = this.getChecked();
        const optName = this.optConfig[optType].name;
        const check = this.optCheck(optType, checkedRows);
        if (!check) {
            return;
        }
        if (content) {
            this.content = '';
        }
        this.modalService.confirm({
            nzTitle: `确认${optName}勾选项？`,
            nzWidth: '600',
            nzContent: content || "",
            nzOnOk: () => {
                const obs = [];
                this.optConfig[optType].optfunc.call(this, checkedRows);
            }
        })
    }

    trDbclick(row) {
        row._tab = this.user.tab;
        this.dbclick.emit(row);
    }

    pageSizeChange(v) {
        this.pageSize = v;
        this.query();
    }
    pageIndexChange(v) {
        this.pageIndex = v;
        this.query();
    }


    getBm() {
        if (this.bmList.length) {
            return;
        }
        const param: any = { showSeg: 1, showAll: 1 };
        const dataurl = environment.apiBase + '/csmis/getKmnOrgTree.jwt';
        this.http.get(dataurl, param).subscribe(res => {
            this.bmList = res;
        })
    }


    getHistory(row) {
        this.weekWorkService.getHistory({ mid: row.nId }).subscribe(res => {
            this.hisTableData = res.data;
        })
    }

    addModal() {
        this.addData = {};
        this.addVisible = true;
    }
    addCancel() {
        this.addVisible = false;
    }

    ymChange(v) {
        const ym = this.getYm(v);
        this.addData._year = ym[0];
        this.addData._month = ym[1];
        this.setS_Edate();
    }
    weekChange(v) {
        this.addData._week = v;
        this.setS_Edate();
    }
    setS_Edate() {
        if (!(this.addData._year && this.addData._month && this.addData._week)) {
            return;
        }
        const param = {
            year: this.addData._year,
            month: this.addData._month,
            weekIndex: this.addData._week,
        }
        this.weekWorkService.getSdate_Edate(param).subscribe(res => {
            const se = res.response.data[0];
            if (this.addData._dtWsdate) {
                this.addData._dtWsdate = se.STARTDATE.replace(' 00:00:00', '');
            }
            if (this.addData._dtWedate) {
                this.addData._dtWedate = se.ENDDATE.replace(' 00:00:00', '');
            }
        });
    }

    _optFunc_delete(rows) {
        if (!rows || !rows.length) {
            return;
        }
        const ids = [];
        rows.forEach(row => {
            ids.push(row.nId);
        });
        if (!ids.length) {
            return;
        }
        this.weekWorkService.delete(ids).subscribe(res => {
            if (res.msg === 'Ok') {
                this.message.success('删除成功');
                this.query();
            } else {
                this.message.warning('删除失败');
            }
        });
    }

    _optFunc_tibao(rows) {
        if (!rows || !rows.length) {
            return;
        }
        const ids = [];
        rows.forEach(row => {
            ids.push(row.nId);
        });
        if (!ids.length) {
            return;
        }
        const param: any = { nId: ids.join() };
        this.weekWorkService.tibao(param).subscribe(res => {
            if (res.msg === 'Ok') {
                this.message.success('提报成功');
                this.query();
            } else {
                this.message.warning('提报失败');
            }
        });
    }

    _optFunc_reset(rows) {
        if (!rows || !rows.length) {
            return;
        }
        const row = rows[0];
        const param = {
            "year": row.vcYear || '',
            "month": row.vcMonth || '',
            "weekIdx": row.vcWeeknum || ''
        }
        this.weekWorkService.reset(param).subscribe(res => {
            if (res.msg === 'Ok') {
                this.message.success('重置成功');
                this.addCancel();
                this.query();
            } else {
                this.message.warning('重置失败');
            }
        })
    }

    _optFunc_bohui(rows) {
        if (!rows || !rows.length) {
            return;
        }
        const ids = [];
        rows.forEach(row => {
            ids.push(row.nId);
        });
        if (!ids.length) {
            return;
        }
        let status;
        switch (this.user.userType) {
            case 'dz':
                status = '5';
                break;
            case 'jskz':
                status = '7';
                break;
            case 'gcs':
                status = '7';
                break;
            case 'cj':
                status = '3';
                break;
            default:
                break;
        }
        const param: any = { nId: ids.join(), vcStatus: status, content: this.content };
        this.weekWorkService.bohui(param).subscribe(res => {
            if (res.msg === 'Ok') {
                this.message.success('驳回' + '成功');
                this.query();
            } else {
                this.message.warning('驳回' + '失败');
            }
        });
    }

    _optFunc_pizhun(rows) {
        if (!rows || !rows.length) {
            return;
        }
        const ids = [];
        rows.forEach(row => {
            ids.push(row.nId);
        });
        if (!ids.length) {
            return;
        }
        let status;
        switch (this.user.userType) {
            case 'dz':
                status = '4';
                break;
            case 'jskz':
                status = '6';
                break;
            case 'gcs':
                status = '6';
                break;
            case 'cj':
                status = '2';
                break;
            default:
                break;
        }
        const param: any = { nId: ids.join(), vcStatus: status, content: this.content };
        this.weekWorkService.pizhun(param).subscribe(res => {
            if (res.msg === 'Ok') {
                this.message.success('批准' + '成功');
                this.query();
            } else {
                this.message.warning('批准' + '失败');
            }
        });
    }
}